package com.wh.blockquene;

/**
 * 
 *  Class Name: TestWaitAndNotify.java
 *  @author wanghao  DateTime 2016年7月26日 上午11:45:05 
 *  @company hongbo
 *  @email 1228675455@qq.com
 *  Description: 当没有明确的对象作为锁，只是想让一段代码同步时，可以创建一个特殊的instance变量（它得是一个对象）来充当锁。
 *  注：零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码。
 */
public class TestWaitAndNotify4 {

	public static void main(String[] args) {
		
		StudentDao dao = new StudentDao();
		 Thread t1 = new Thread(new TestThread(dao)); 
		 Thread t2 = new Thread(new TestThread(dao));
		 t1.start();
		 t2.start();
	}
	
	static class StudentDao {
		
		public void addStudent() {
			System.out.println("线程:" + Thread.currentThread().getName() + " 非同步代码块部分");
			synchronized(this) {
				System.out.println("增加开始");
				try {
					System.out.println("线程开始等待！");
					Thread.currentThread().sleep(10000);
					System.out.println("线程等待结束！");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("增加结束");
			}
		}
		
		public void deleteStudent() {
				System.out.println("删除开始");
				try {
					Thread.currentThread().sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("删除结束");
		}
	}
	
	static class TestThread implements Runnable {

		private static byte[] lock = new byte[0];
		
		private StudentDao studentDao;
		
		public TestThread(StudentDao studentDao) {
			super();
			this.studentDao = studentDao;
		}

		@Override
		public void run() {
/*			synchronized(lock) {
				System.out.println("线程:" + Thread.currentThread().getName() + "Test");
				studentDao.deleteStudent();
			}*/
			studentDao.addStudent();
		}
		
	}
	
}
